package com.hbisedm.interninfosys.intern.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hbisedm.interninfosys.commonutils.R;
import com.hbisedm.interninfosys.intern.entity.*;
import com.hbisedm.interninfosys.intern.entity.queryVo.UserQuery;
import com.hbisedm.interninfosys.intern.entity.vo.IdentifyVo;
import com.hbisedm.interninfosys.intern.entity.vo.RelevanceUserVo;
import com.hbisedm.interninfosys.intern.entity.vo.ReportVo;
import com.hbisedm.interninfosys.intern.service.IStuInternshipService;
import com.hbisedm.interninfosys.intern.service.IUserInternshipService;
import com.hbisedm.interninfosys.intern.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 *  实习
 * </p>
 *
 * @author Sam
 * @since 2020-12-03
 */
@RestController
@RequestMapping("/intern/user-internship")
@Api(tags = {"实习记录管理"})
public class UserInternshipController {
    @Autowired
    IUserInternshipService userInternshipService;
    @Autowired
    IUserService userService;
    @Autowired
    IStuInternshipService stuInternshipService;

    @PostMapping("/list/{current}/{limit}")
    public R evaluateList(@PathVariable long current,
                          @PathVariable long limit,
                          @RequestBody(required = false) UserQuery internshipQuery) {
        /**
         * todo 创建query entity 搜索相应的内容
         */
        Page<UserInternship> userInternshipPage = new Page<>(current, limit);
        QueryWrapper<UserInternship> userInternshipQueryWrapper = new QueryWrapper<>();
        String associationName = internshipQuery.getAssociationName();
        if(!StringUtils.isEmpty(associationName)) {
            User one1 = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getUsername, associationName));
            Integer iid = one1.getId();
            List<StuInternship> list = stuInternshipService.list(new QueryWrapper<StuInternship>().lambda().eq(StuInternship::getIid, iid));

            ArrayList<Integer> sids = new ArrayList<>();
            list.forEach(item-> {
                sids.add(item.getSid());
            });

            userInternshipQueryWrapper.lambda().in(UserInternship::getSid, sids);
        }

        userInternshipService.page(userInternshipPage,userInternshipQueryWrapper);
        List<UserInternship> list = userInternshipPage.getRecords();
        for (UserInternship internship : list) {
            Integer sid = internship.getSid();
            User stu = userService.getById(sid);
            StuInternship one = stuInternshipService.getOne(new QueryWrapper<StuInternship>().lambda().eq(StuInternship::getSid, sid));
            Optional<StuInternship> optional = Optional.ofNullable(one);
            if (optional.isPresent()) {
                StuInternship internship1 = optional.get();
                Integer iid = internship1.getIid();
                User one1 = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getId, iid));
                internship.setInternName(one1.getOthername());
            }
            internship.setStuName(stu.getOthername());
            internship.setStuId(stu.getUsername());
        }

        return R.ok()
                .data("userInternships", list)
                .data("total", userInternshipPage.getTotal());
    }

    @PostMapping("/add")
    public R addInternship(@RequestBody UserInternship userInternship) {
        System.out.println(userInternship);
        boolean b = userInternshipService.saveOrUpdate(userInternship);
        if(b) {
            return R.ok();
        }else {
            return R.error();
        }
    }

    @GetMapping("/getStuStatus")
    public R getStuStatus() {
        List<UserInternship> list = userInternshipService.list(new QueryWrapper<UserInternship>().lambda().eq(UserInternship::getDeleted, 0));
        HashMap<String, Object> map = new HashMap<>();

        AtomicInteger success= new AtomicInteger();
        AtomicInteger fail= new AtomicInteger();
        list.forEach(item -> {
            if (item.getStatus() == 2) {
                success.getAndIncrement();
            }else {
                fail.getAndIncrement();
            }
        });
        String[] text = new String[]{"成功", "失败"};
        int[] nums = new int[]{success.get(), fail.get()};
        map.put("text", text);
        map.put("nums", nums);
        return R.ok().data(map);
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除实习记录")
    public R removeInternship(@PathVariable @ApiParam("通过Id进行删除") Integer id) {
        boolean b = userInternshipService.removeById(id);
        if(b) {
            return R.ok();
        }else {
            return R.error();
        }
    }

    @GetMapping("/info/{id}")
    @ApiOperation(value = "获取实习记录信息")
    public R getInfo(@PathVariable @ApiParam("通过ID进行获取") Integer id) {
        UserInternship userInternship = null;
        userInternship = userInternshipService.getOne(new QueryWrapper<UserInternship>().lambda().eq(UserInternship::getSid,id).eq(UserInternship::getDeleted, 0));
        if(userInternship != null) {
            userInternship.setStuName(userService.getById(userInternship.getSid()).getOthername());
            StuInternship one = stuInternshipService.getOne(new QueryWrapper<StuInternship>().lambda().eq(StuInternship::getSid, id));
            if(one!=null) {
                userInternship.setInternName(userService.getById(one.getIid()).getOthername());
            }
        }
        return R.ok().data("internship", userInternship);
    }

    @PostMapping("/updateTime")
    @ApiOperation("修改时间")
    public R updateTime(@RequestBody UserInternship userInternship) {
        UserInternship one = userInternshipService.getOne(new QueryWrapper<UserInternship>().lambda().eq(UserInternship::getSid, userInternship.getSid()));
        one.setInternshipEndTime(userInternship.getInternshipEndTime());
        one.setInternshipStartTime(userInternship.getInternshipStartTime());
        boolean b = userInternshipService.updateById(one);
        return R.ok().data("status", b);
    }

    @GetMapping("/changeStatus/{sid}")
    @ApiOperation("修改实习鉴定表审核状态为1")
    public R changeStatus(@PathVariable Integer sid) {
        UserInternship one = userInternshipService.getOne(new QueryWrapper<UserInternship>().lambda().eq(UserInternship::getSid, sid).eq(UserInternship::getDeleted, 0));
        /**
         * 设置为1 表示审核ing
         */
        one.setStatus(1);
        boolean b = userInternshipService.updateById(one);
        return R.ok().data("change", b);
    }

    @Autowired
    StuInternshipController stuInternshipController;

    @PostMapping("addTeacherOption")
    @ApiOperation(value = "添加教师意见")
    public R addTeacherOption(@RequestBody UserInternship userInternship,
                              ModelMap modelMap, HttpServletRequest request,
                              HttpServletResponse response) {
        /**
         * 暂时没有老师签名
         */
        if (userInternship.getTeacherOpinion().isEmpty() && userInternship.getTeacherGrade() == null) {
            System.out.println();
            userInternship.setTeacherGrade(0);
            /**
             * 设置状态为审核ing，
             */
            userInternship.setStatus(1);
            userInternshipService.updateById(userInternship);

        } else {
            userInternshipService.updateById(userInternship);

            if(userInternship.getTeacherGrade()!=null && userInternship.getTeacherGrade() >= 0 && userInternship.getInternshipGrade() != null && userInternship.getInternshipGrade() >= 0) {
                stuInternshipController.download01(userInternship, modelMap, request, response);
            }
        }


        return R.ok();
    }

    @PostMapping("addInternshipOption")
    @ApiOperation(value = "添加实习单位意见")
    public R addInternshipOption(@RequestBody UserInternship userInternship,
                                 ModelMap modelMap, HttpServletRequest request,
                                 HttpServletResponse response) {
        /**
         * 暂时没有企业盖章
         */

        if (userInternship.getInternshipOpinion().isEmpty() && userInternship.getInternshipGrade() == null) {
            userInternship.setInternshipGrade(0);
            /**
             * 设置状态为审核ing
             */
            userInternship.setStatus(1);
            userInternshipService.updateById(userInternship);
        } else {
            userInternshipService.updateById(userInternship);

            if(userInternship.getTeacherGrade()!=null && userInternship.getTeacherGrade() >= 0 && userInternship.getInternshipGrade() != null && userInternship.getInternshipGrade() >= 0) {
                stuInternshipController.download01(userInternship, modelMap, request, response);
            }
        }

        return R.ok();
    }

    @GetMapping("/getInternshipStatus/{sid}")
    @ApiOperation("获取实习鉴定表的审核状态")
    public R getInternshipStatus(@PathVariable Integer sid) {
        UserInternship one = userInternshipService.getOne(new QueryWrapper<UserInternship>().lambda().eq(UserInternship::getSid, sid).eq(UserInternship::getDeleted, 0));
        boolean a = true;
        boolean b = true;
        if (one != null) {
            if (one.getTeacherGrade() != null &&  one.getTeacherGrade() > 0) {

            }else {
                a = false;
            }
            if(one.getInternshipGrade() != null && one.getInternshipGrade() > 0) {

            }else {
                b = false;
            }
        }

        if (a && b) {
            return R.ok().data("status", true);
        }
        return R.ok().data("status", false);
    }




    @PostMapping("/addReport")
    @ApiOperation("添加实习报告")
    public R addReport(@RequestBody ReportVo reportVo) {
        UserInternship one = userInternshipService.getOne(new QueryWrapper<UserInternship>().lambda().eq(UserInternship::getSid, reportVo.getSid()).eq(UserInternship::getDeleted, 0));
        Optional<UserInternship> one1 = Optional.ofNullable(one);
        if (one1.isPresent()) {
            UserInternship userInternship = one1.get();
            BeanUtils.copyProperties(reportVo, userInternship);
            userInternship.setInternshipReportStatus(true);
            userInternshipService.updateById(userInternship);
        }else {
            UserInternship userInternship = new UserInternship();
            BeanUtils.copyProperties(reportVo, userInternship);
            userInternship.setInternshipReportStatus(true);
            userInternshipService.save(userInternship);
        }
        return R.ok();
    }


    @PostMapping("/addIdentify")
    @ApiOperation("添加周志")
    public R addIdentify(@RequestBody IdentifyVo identifyVo) {
        if(StringUtils.isEmpty(identifyVo.getInternshipRecordContentOne())
                || StringUtils.isEmpty(identifyVo.getInternshipRecordContentTwo())
                || StringUtils.isEmpty(identifyVo.getInternshipRecordContentThree())
                || StringUtils.isEmpty(identifyVo.getInternshipRecordContentFour())) {
            return R.error();
        }
        UserInternship one = userInternshipService.getOne(new QueryWrapper<UserInternship>().lambda().eq(UserInternship::getSid, identifyVo.getSid()));
        BeanUtils.copyProperties(identifyVo, one);
        one.setInternshipRecordStatus(true);
        userInternshipService.saveOrUpdate(one);

        return R.ok();
    }

    @PostMapping("/addAuthenticate")
    @ApiOperation("添加自我鉴定")
    public R addAuthenticate(@RequestBody UserInternship userInternship) {
        if(StringUtils.isEmpty(userInternship.getInternshipSummaryContent()) || StringUtils.isEmpty(userInternship.getSid())) {
            return R.error().message("总结内容为空");
        }else {
            UserInternship one = userInternshipService.getOne(new QueryWrapper<UserInternship>().lambda().eq(UserInternship::getSid, userInternship.getSid()));
            one.setInternshipSummaryContent(userInternship.getInternshipSummaryContent());
            one.setInternshipSummaryStatus(true);
            boolean b = userInternshipService.saveOrUpdate(one);
            if(b) {
                return R.ok();
            }
        }
        return R.error();
    }


    @GetMapping("/getRelevanceUser/{id}")
    @ApiOperation("审核状态")
    public R getRelevanceUser(@PathVariable Integer id) {
        User user = userService.getById(id);
        new ArrayList<RelevanceUserVo>();
        if(user.getType() == 2) {

        }
        if(user.getType() == 3) {

        }
        return R.ok();
    }

}
